#include <hardware.h>

#define RTC_SEC 0x00 // Clock Enabled | 00 Seconds
#define RTC_MIN 0x00 // 00 Minutes
#define RTC_HR 0x12 // 24 HOUR CLOCK | 12
#define RTC_DAY 0x07 // Saturday
#define RTC_DATE 0x01 // 01
#define RTC_MON 0x01 // January
#define RTC_YR 0x11 // 2011
#define RTC_CON 0x80 // OUT HIGH | Square Wave Disabled | 1 Hz

extern volatile unsigned char full_messages;

void rtc_write(unsigned char *rtc_msg, unsigned char mode)
{
unsigned char twi_rtc_set_msg[] = {RTC_W, 0x00, RTC_SEC, RTC_MIN, RTC_HR, RTC_DAY, RTC_DATE, RTC_MON, RTC_YR, RTC_CON};
unsigned char twi_rtc_set_msg_length = 10;

if (mode == 1)
    {
    twi_rtc_set_msg[2] = rtc_msg[0];
    twi_rtc_set_msg[3] = rtc_msg[1];
    twi_rtc_set_msg[4] = rtc_msg[2];
    twi_rtc_set_msg[5] = rtc_msg[3];
    twi_rtc_set_msg[6] = rtc_msg[4];
    twi_rtc_set_msg[7] = rtc_msg[5];
    twi_rtc_set_msg[8] = rtc_msg[6];
    }

send_twi_msg(twi_rtc_set_msg, twi_rtc_set_msg_length);
}

void rtc_read(unsigned char *rtc_msg)
{
unsigned char twi_rtc_point_msg[] = {RTC_W, 0x00};
unsigned char twi_rtc_point_msg_length = 2;

if (full_messages == 1)
    {
    strf2buffer("Checking Time\r");
    }

send_twi_msg(twi_rtc_point_msg, twi_rtc_point_msg_length);
    
if (twi_read(rtc_msg, RTC_R, 7) != 7)
    {
    rtc_msg[0] = RTC_SEC;
    rtc_msg[1] = RTC_MIN;
    rtc_msg[2] = RTC_HR;
    rtc_msg[3] = RTC_DAY;
    rtc_msg[4] = RTC_DATE;
    rtc_msg[5] = RTC_MON;
    rtc_msg[6] = RTC_YR;
    }
//while (twi_read(rtc_msg, RTC_R, 7) != 7)
//    {
//    send_twi_msg(twi_rtc_point_msg, twi_rtc_point_msg_length);
//    }
}